<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use App\Http\Controllers\Controller;
use App\Models\Content;
use App\Models\Message;
use App\Models\UserCollection;
use Illuminate\Http\Request;

class UserCollectController extends ApiController
{
    public function collect(Request $request)
    {
        $content_id = $request->input('content_id');
       
        if (empty($content_id)) {
            return $this->errorReturn('param error');
        }
        $userId = app('userId');
        if (!$userId) {
            return $this->errorReturn('请先登录');
        }
        $isExists = UserCollection::where('user_id', $userId)
            ->where('content_id', $content_id)
            ->count();
        if (!$isExists) {
            // 收藏
            $content = Content::find($content_id);
            if (empty($content->id)) {
                return $this->errorReturn('entity not found');
            }
            $content->UserCollections()->save(new UserCollection([
                'user_id' => $userId,
                'content_type' => $content->type,
            ]));
            // 发送消息通知
            $message = new Message([
                'receive_user_id' => $userId,
                'send_user_id' => 0,
                'content_id' => $content_id,
                'type' => 1,
                'title' => '收藏成功',
            ]);
            $message->save();
            
        }
        return $this->okReturn(1);
    }

    public function uncollect(Request $request)
    {
        $content_id = $request->input('content_id');
       
        if (empty($content_id)) {
            return $this->errorReturn('param error');
        }
        $userId = app('userId');
        if (!$userId) {
            return $this->errorReturn('请先登录');
        }
        $isExists = UserCollection::where('user_id', $userId)
            ->where('content_id', $content_id)
            ->count();
        if ($isExists) {
            // 取消收藏
            $content = Content::find($content_id);
            if (empty($content->id)) {
                return $this->errorReturn('content not found');
            }
            $content->UserCollections()->where('user_id', $userId)
                ->where('content_type', $content->type)
                ->delete();
            // 发送消息通知
            $message = new Message([
                'receive_user_id' => $userId,
                'send_user_id' => 0,
                'content_id' => $content_id,
                'type' => 1,
                'title' => '取消收藏',
            ]);
            $message->save();
        }
        return $this->okReturn(1);
    }
}
